#include "em_i2c.h"
#include "em_cmu.h"
#include "../../hardware/kit/common/drivers/i2cspm.h"
#include "hal/plugin/i2c-driver/i2c-driver.h"

void si7021_hal_delay_ms(uint32_t ms)
{
	halCommonDelayMilliseconds((uint16_t)ms);
}

uint8_t	si7021_hal_i2c_write_device(uint8_t addr, uint8_t *data, uint8_t len)
{
    I2C_TransferReturn_TypeDef ret;
	ret = halI2cWriteBytes(addr<<1, data, len);
	if (ret != I2C_DRIVER_ERR_NONE) {
		return ((uint8_t) 0);
	}
	else{
		return ((uint8_t) 1);
	}
}

uint8_t	si7021_hal_i2c_read_device(uint8_t addr, uint8_t *data, uint8_t len)
{
  	I2C_TransferReturn_TypeDef ret;
	ret =  halI2cReadBytes(addr<<1, data, len);
	if (ret != I2C_DRIVER_ERR_NONE) {
		return ((uint8_t) 0);
	}
	else{
		return ((uint8_t) 1);
	}
}

uint8_t si7021_hal_i2c_read_device_reg(uint8_t dev_addr, uint8_t reg_addr, uint8_t* pu8Data, uint8_t u8Length)
{
	I2C_TransferSeq_TypeDef seq;
	I2C_TransferReturn_TypeDef ret;
	uint8_t i2c_write_data[1];

	seq.addr = dev_addr<<1;
	seq.flags = I2C_FLAG_WRITE_READ;

	/* Select command to issue */
	i2c_write_data[0] = reg_addr;
	seq.buf[0].data = i2c_write_data;
	seq.buf[0].len = 1;

	/* Select location/length of data to be read */
	seq.buf[1].data = pu8Data;
	seq.buf[1].len = u8Length;

	ret = I2CSPM_Transfer(I2C0, &seq);

	if (ret != i2cTransferDone) {
		return ((uint8_t) 0);
	}
	else{
		return ((uint8_t) 1);
	}
}

uint8_t si7021_hal_i2c_write_device_reg(uint8_t u8Address, uint8_t u8Command, uint8_t* pu8Data, uint8_t u8Length)
{
	I2C_TransferSeq_TypeDef seq;
	I2C_TransferReturn_TypeDef ret;
	uint8_t i2c_write_data[1];

	seq.addr = u8Address<<1;
	seq.flags = I2C_FLAG_WRITE_WRITE; // S+ADDR(W)+DATA0+DATA1+P.

	/* Select command to issue */
	i2c_write_data[0] = u8Command;
	seq.buf[0].data = i2c_write_data;
	seq.buf[0].len = 1;

	/* Select location/length of data to be read */
	/*fulfill the read buffer even the flag indicate doing write only*/
	seq.buf[1].data = pu8Data;
	seq.buf[1].len = u8Length;

	ret = I2CSPM_Transfer(I2C0, &seq);

	if (ret != i2cTransferDone) {
		return ((uint8_t) 0);
	}
	else{
		return ((uint8_t) 1);
	}
}